package top.broncho.lottery.ui.base

import android.os.Bundle
import android.view.MenuItem
import androidx.annotation.LayoutRes
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import org.jetbrains.anko.AnkoLogger
import org.jetbrains.anko.info
import top.broncho.lottery.util.LotteryDataBindingComponent

abstract class BaseActivity<T : ViewDataBinding> : AppCompatActivity(), AnkoLogger,
    CoroutineScope by MainScope() {
    var binding by autoCleared<T>()

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (isDisplayHomeAsUpEnabled()) {
            supportActionBar?.setDisplayHomeAsUpEnabled(true)
        }
        binding = DataBindingUtil.setContentView(this, getLayoutId(), LotteryDataBindingComponent())
    }

    open fun isDisplayHomeAsUpEnabled() = true

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
        }
        return super.onOptionsItemSelected(item)
    }

    @LayoutRes
    abstract fun getLayoutId(): Int

    override fun onDestroy() {
        super.onDestroy()
        info { "onDestroy" }
        cancel()
    }
}